<?php
namespace common\utils;
use common\models\Article;
use common\models\Category;
use common\models\InnnerLink;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

/**
 * Created by PhpStorm.
 * User: Duyonggao
 * Date: 2017/12/14 0014
 * Time: 下午 5:16
 */
class Com
{
    public static function v(){
        return '20180914009';
    }
    
    public static function cats(){
        return \Yii::$app->cache->getOrSet('com.cats',function(){
            return Category::find()->select(['id','pid','name'])->asArray()->all(); 
        },60);
    }
    
    public static function isMobileNum($num){
        return preg_match('/^\d{11}$/',$num);
    }

    public static function isMobile(){
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }

        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap"))
        {
            return  true ;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile',
                'micromessenger'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }

    public static function isM(){
        return substr($_SERVER['HTTP_HOST'],0,2) == 'm.';
    }

    public static function jumpM(){
        if(self::isMobile() && !static::isM()){
            \Yii::$app->controller->redirect(static::urlM());
        }
    }

    public static function urlM(){
        $url = \Yii::$app->request->absoluteUrl;
        $url = preg_replace('/http:\/\//','',$url);
        $arr = explode('.',$url);
        if(isset($arr[0])){
            $arr[0] = 'm';
        }
        $url = 'http://'.implode('.',$arr);
        return $url;
    }
    public static function urlWww(){
        $url = \Yii::$app->request->absoluteUrl;
        $url = preg_replace('/http:\/\//','',$url);
        $arr = explode('.',$url);
        if(isset($arr[0])){
            $arr[0] = 'www';
        }
        $url = 'http://'.implode('.',$arr);
        return $url;
    }

    public static function reUrl($content){
        return preg_replace('/http:\/\/www\.angzhui\.cn/','http://m.angzhui.cn',$content);
    }

    public static function urlHelp($id){
        return "/help/{$id}.html";
    }

    public static function urlCat($id = ""){
        $key = 'urlCat'.$id;
        $url = \Yii::$app->cache->get($key);
        if(!empty($url)){
            return $url;
        }
        $row = Category::find()->select(['py'])->where(['id'=>$id])->asArray()->one();
        if (empty($row)){
            $url = "/news/";
            \Yii::$app->cache->set($key,$url);
        }else{
            $url = "/{$row['py']}/";
        }
        \Yii::$app->cache->set($key,$url,86400);
        return $url;
    }

    public static function urlNews($id){
        $key = 'urlnews'.$id;
        $url = \Yii::$app->cache->get($key);
        if(!empty($url)){
            return $url;
        }
        $row = Article::findOne($id);
        if (empty($row)){
            $url = "/news/{$id}.html";
            \Yii::$app->cache->set($key,$url);
        }else{
            $url = "/{$row['cats']['py']}/{$row['id']}.html";
        }
        \Yii::$app->cache->set($key,$url,86400);
        return $url;
    }

    public static function reUrlNews($page){
        $cat = \Yii::$app->request->get("cat");
        $page = $page+1;
        if($page != 1){
            if(empty($cat)){
                $url = "/news/{$page}/";
            }else{
                $url = "/{$cat}/{$page}/";
            }
        }else{
            if(empty($cat)){
                $url = "/news/";
            }else{
                $url = "/{$cat}/";
            }
        }
        return $url;
    }

    const PIC_HOST = 'http://img.angzhui.cn';
    public static function pic($pic){
        return self::PIC_HOST.$pic;
    }
    public static $countImg = 0;
    public static $ext = '';
    //<img src="/upload/caiji/201710_list_607_1.jpg" class="lazy" width="750">
    //{品牌}{名称}{特点}效果图片欣赏{id}
    public static function contentImg($content,$ext = ''){
        static::$ext =  $ext.'效果图片欣赏';
        return preg_replace_callback('/\<img(.*?)src=[\"\'](\/upload\/.*?)[\"\'](.*?)\>/',function($match){
            static::$countImg ++;
            $ext = static::$ext.static::$countImg;
            return "<img{$match[1]}src=\"".self::df()."\" alt=\"{$ext}\" data-img=\"".self::PIC_HOST."{$match[2]}\"{$match[3]}>";
        },$content);
//        return preg_replace('/\<img(.*?)src=[\"\'](\/upload\/.*?)[\"\'](.*?)\>/',"<img$1src=\"".self::df()."\" data-img=\"".self::PIC_HOST."$2\"$3>",$content);
    }

    public static function df($pic=''){
        return Url::to("/img/load.png",true);
    }

    public static function site($url){
        return \Yii::$app->params['site'].$url;
    }

    public static function Push($urls){
        if(empty($urls)){
            return false;
        }
        $api = 'http://data.zz.baidu.com/urls?site=www.angzhui.cn&token=R42yNCsiewUwOPea';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        $ok = json_encode($result,true);
        return isset($ok['success']) && $ok['success']>0 ? $ok['success'] : 0;
    }

    public static function Link($text){
        $text = strip_tags($text,"<b><img><a><style><p><br>");
        $text = preg_replace('/www\.szfangwei\.cn/','www.angzhui.cn',$text);
        $tmp = preg_replace('/\<a[^\>]*?\>.*?\<\/a\>/','',$text);
        $tmp = preg_replace('/\<img.*?\>/','',$tmp);
        $links = static ::getInnerLink();
        if(!empty($links)){
            $arr_p = [];
            $match = 0;
            foreach ($links as $k=>$vo){
                if($match < 5){
                    if(preg_match('/(.{0,6})('.preg_quote($k).')(.{0,6})/',$tmp,$out)){
                        $match++;
                        $arr_p[] = [$out[1],$out[2],$out[3],$vo];
                    }
                }
            }
            if(!empty($arr_p)){
                foreach ($arr_p as $vo){
                    $text = preg_replace('/'.preg_quote($vo[0],'/').''.preg_quote($vo[1],'/').''.preg_quote($vo[2],'/').'/',$vo[0].'<a href="'.$vo[3].'" target="_blank">'.$vo[1].'</a>'.$vo[2],$text,1);
                }
            }
        }
        $text = preg_replace('/400-800-9385/','18884008117',$text);
        return $text;
    }

    public static function getInnerLink(){
        $key = 'getInnerLink2';
        $data = \Yii::$app->cache->get($key);
        if(empty($data)){
            $links = InnnerLink::find()->asArray()->all();
            if(empty($links)){
                return [];
            }
            $data = ArrayHelper::map($links,'word','name');
            \Yii::$app->cache->set($key,$data,60);
        }
        return $data;
    }
}